<?
  include ("../../../../admin/config/cfg.php");
  global $cwlang, $cwLanguage;
 	sajax_init();
  
  //================ PAGE LOGIC ================

  if (count($_POST)>0) {
    $entry=Array(
      "name"        => $_POST["name"],
    //"trunk_order" => $_POST["trunk_order"],
      "port"        => $_POST["listRight"], 
      "msns"        => $_POST["phonenumber"], 
    //"rule"        => $_POST["rule"],
      "speeddial"   => $_POST["speeddial"],
      "type"        => $_POST["type"],
      "did"         => $_POST["did"],
      "signalling"  => $_POST["signalling"]
    ); 

    // add options to the entry

    foreach ($_POST as $k=>$v) {
      if (substr($k,0,7)=="status_") {
        $k=substr($k,7);
        if ($v=="1") {
          $o["key"]=$k; 
          $o["value"]=$_POST["option_".$k];
          $options[]=$o;
        }
      }
    }
    $entry["option"]=$options;
    
    // insert new entry or modify only??

    if (isset($_POST["id"])) {
      $entry["id"]=$_POST["id"];
    }

    // save the group informations

    $ret=$asterisk->putZapataGroup($entry);

    if ($ret > 0) {
      $alert="<div class=\"AlertGood\">".$cwlang["zapatagrp"]["alertModGood"]."</div>";
      $_GET["id"]=$ret;
    } else { 
      $alert="<div class=\"AlertBad\">".$cwlang["zapatagrp"]["alertModBad"]."</div>";
    } 
    goToMainPage($alert,"../groups.php");
  }

  //--------------------------------------------------------------------------
  
  // if modify, read the group informations

  if (isset($_GET["id"])) {
    $ret=$asterisk->getZapataGroup($_GET["id"]);
    if ($err=$asterisk->getError()) die("Error: $err");

    $id          = $ret[0]["id"];
    $name        = $ret[0]["name"];
    $rule        = $ret[0]["rule"];
    $speeddial   = $ret[0]["speeddial"];
    $trunk_order = $ret[0]["trunk_order"];
    $groupPort   = $ret[0]["port"];
    $groupOption = $ret[0]["option"];
    $type        = $ret[0]["type"];
    $did         = $ret[0]["did"];
    $signalling  = $ret[0]["signalling"];

    if (is_array($ret[0]["msns"]))
    foreach ($ret[0]["msns"] as $n) {
      $numbers.="<option value=\"$n\">$n</option>";
    }
  } else {
    $type=$_GET["portType"];
  } 

  // get the ports, channel informations

  $id=$_GET["id"];

  $ret=$asterisk->getZapataChannel(0);
  if ($err=$asterisk->getError()) die("Error: $err");

  $old_card_id = 0;
  $old_port_id = 0;

  if ($type == "PRI") {
    $choose_signalling[] = "pri_cpe";
    $choose_signalling[] = "pri_net";
  }
  if ($type == "E&M") {
    $choose_signalling[] = "em";
    $choose_signalling[] = "em_w";
  }
  if ($type == "FXO") {
    $choose_signalling[] = "fxs_ks";
    $choose_signalling[] = "fxs_ls";
    $choose_signalling[] = "fxs_gs";
  }
  if ($type == "FXS") {
    $choose_signalling[] = "fxo_ks";
    $choose_signalling[] = "fxo_ls";
    $choose_signalling[] = "fxo_gs";
  }
  $option_signalling = "";
  foreach ($choose_signalling as $s) {
    if ($s==$signalling) $chk_opt=" selected "; else $chk_opt="";
      $option_signalling.="<option $chk_opt>".$s;
  }

  if (is_array($ret)) {
    foreach($ret as $v) {
      $portid    = $v["id"];        // Channel Id from channel table 

      // This one should skip ports that are not valid or not requested

      if ($v["type"]   != $type)     continue;
      if ($v["device"] == "unused" ) continue;

      $available = $v["available"];
      $port_id   = $v["port_id"];   // Port Id number

      // We should only have valid entries to show here !!!

      if ($type == 'FXO' || $type == 'FXS') {
        $pchannel = $v["pchannel"];
        $chaninfo = ",".$pchannel;
      } else {
        $chaninfo = "";
      }

      // Show only one entry for PRI and E&M, anyhow you can only
      // assign the whole port while channelbanks are different 

      if ($old_port_id == $port_id && $type == 'PRI') {
        continue; // Show only the whole port here
      }

      if ($old_port_id == $port_id && $type == 'E&M') {
        continue; // Show only the whole port here
      }

      // If we have a new port, get the new card_id

      if ($old_port_id != $port_id) { // We have a new port
        $p=$asterisk->getZapataPort($port_id);
        $card_id = $p[0]["card_id"];  
        $card    = $p[0]["card"];
        $port    = $p[0]["port"];
        $old_port_id = $port_id;
      }

      if ($old_card_id != $card_id) { // We have a new card
        $c=$asterisk->getZapataCard($card);
        $cardfullname = explode(" ", $c[0]["name"]);
        $cardnickname = $cardfullname[0]; // Name until first space
      }

      if (@in_array($portid,$groupPort)) $portsRight.="<option value=\"$portid\" >$cardnickname - Port $port$chaninfo ($portid) </option>";    
      else if ($available==1 ) $portsLeft.="<option value=\"$portid\" >$cardnickname - Port $port$chaninfo ($portid) </option>";    
      $old_card_id=$card_id;
    }  
  }

  // get the options 

  $html=getOption(OPTION_ZAPATA_GROUPS,$groupOption);
  
  //================ MAIN CONTENTS ================
  ob_start();
  ?>

  <? $sel="groups"; include ("../navigation.php");?>
  
  <div class="SectionHeader">
    <?=$alert?>
    <h1><?=$cwlang["zapatagrp"]["title"]?> (<?=$type?>)</h1>
    <h3><a href="../groups.php" class="admin" ><?=$cwlang["zapatagrp"]["return"]?></a></h3>
  </div>
  
  <div id="basic_form">
    <form action="<?=$PHP_SELF?><?if (isset($_GET["id"])) echo "?id=".$_GET["id"];?>" method="post" onSubmit="selectAll(getElementById('listRight')); return selectAll(getElementById('phonenumber'))">
      
      <p class="blockintro"><?=$cwlang["zapatagrp"]["titleDesc"]?></p>
      <div class="block">
        <table>
          <tr>
            <td class="required"><label for="group[name]"><?=$cwlang["zapatagrp"]["groupName"]?>:</label></td>
            <td><input type="text" size="25" maxlength="30" id="group[name]" name="name" value="<?=$name?>" /></td>
          </tr>
          <tr>
            <td class="required"><label for="speeddial"><?=$cwlang["zapatagrp"][""]?>Speed Dial:</label></td>
            <td>
              <input type="text" name="speeddial" value="<?=$speeddial?>" size="3" maxlength="3"><big><strong>*</strong></big>
              <span class="help">Write a number to speed dial with this trunk. I.e. <strong>1</strong> or <strong>76</strong></span>
              <!-- 
              <input type="text" size="5" maxlength="2" id="group[trunk_order]" name="trunk_order" value="<?=$trunk_order?>" />
              -->
            </td>
          </tr>
          <tr>
            <td class="required"><label for="signalling">Signalling:</label></td>
            <td>
              <select name=signalling><?=$option_signalling?></select>
              <span class="help">Signalling for this Trunkgroup</span>
            </td>
          </tr>
          <tr>
            <td class="help" colspan="2">
              <!--
              <?=$cwlang["zapatagrp"]["enableOutcomingCallHelp"]?>
              -->
            </td>
          </tr>
        </table>
      </div>

    	<h2><?=$cwlang["zapatagrp"]["listeningNumber"]?></h2>
      <p class="blockintro"><?=$cwlang["zapatagrp"]["listeningNumberHelp"]?></p>
      <div class="block">
        <table>
          <tr>
            <td class="required"><label for="number"><?=$cwlang["zapatagrp"]["phoneNumber"]?>:</label></td>
            <td class="required"><?=$cwlang["zapatagrp"]["phoneNumberAdded"]?></td>
          </tr>
          <tr>
            <td valign="top">
              <input type="text" size="25" maxlength="100" id="number" name="number" value="" />
              <input type="button" value="+" onclick="addOption(getElementById('phonenumber'),document.getElementById('number').value); document.getElementById('number').value='' " title="Add Length">
              <div class="help">Digit the numbers to listen (i.e. <strong>123456</strong>)<br/>or a range of numbers as (<strong>123456-123459</strong>)</div>
              <div style="margin: 0.5em 0"><strong>DID:</strong> <?=showDid($did);?></div>
            </td>
            <td>
              <select name="phonenumber[]" size="4" onchange="saved = false" ondblclick="editOptions(this)" multiple style="float: left" id="phonenumber">
                <?=$numbers?>
              </select>
              <input type="button" value="edit" onclick="editOptions(getElementById('phonenumber'))" title="Edit Length(s)">
              <input type="button" value="X" onclick="deleteOptions(getElementById('phonenumber'))" title="Delete Length(s)">
            </td>
          </tr>
        </table>
      </div>
      
    	<h2><?=$cwlang["zapatagrp"]["ports"]?></h2>
      <p class="blockintro"><?=$cwlang["zapatagrp"]["portsDesc"]?></p>
      <div class="block">
        <table border="0">
        <tr>
          <td class="required">
            <div ><?=$cwlang["zapatagrp"]["availablePorts"]?>:</div>
            <select multiple size="5"  name="listLeft[]" id="listLeft"><?=$portsLeft?></select>
          </td>
          <td>   
            <div><input type="button" style="width:90" onclick="moveDualList( document.getElementById('listLeft'),  document.getElementById('listRight'), false )" name="Add     >>"  value="Aggiungi       >>" style="width:100px"></div>
            <div><input type="button" style="width:90" onclick="moveDualList( document.getElementById('listRight'), document.getElementById('listLeft'),  false )" name="Add     <<"  value="<<     Rimuovi" style="width:100px"></div>
            <div><input type="button" style="width:90" onclick="moveDualList( document.getElementById('listLeft'),  document.getElementById('listRight'), true  )" name="Add All >>"  value="Aggiungi tutte >>" style="width:100px"></div>
            <div><input type="button" style="width:90" onclick="moveDualList( document.getElementById('listRight'), document.getElementById('listLeft'),  true  )" name="Add All <<"  value="<< Rimuovi tutto " style="width:100px"></div>
          </td>
          <td class="required"><div ><?=$cwlang["zapatagrp"]["groupPorts"]?>:</div>
            <select multiple size="5" name="listRight[]" id="listRight"><?=$portsRight?></select>
          </td>
        </tr>
        </table>
      </div>

<?    echo listOption($js, ZAP, $groupOption, false, false, RULE_INCOMING);?>   
      
    <?=$numHidden?>      
    <div class="action">
      <?if (isset($_GET["id"])) {?><input type="hidden" name="id" value="<?=$id?>" /><?}?>
      <input type="hidden" name="type" value="<?=$type?>" />
      <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Cancel" onclick="location.href='../groups.php'; return false;"/>
      <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Save" />
    </div>
  </form>
 </div>  
  
  <?
  $contents=ob_get_contents();
  ob_end_clean();

  //================ SIDEBAR ================
  ob_start(); 
  ?>
        <div class="Sidebar">
          <?$sel="zapata";include("../../sidebar.php");?>
          <h1><?=$cwlang["zapatagrp"]["sidebarTitle"]?></h1>
          <p><?=$cwlang["zapatagrp"]["sidebarDesc"]?>
        </div>
  <?  
  $sidebar=ob_get_contents();
  ob_end_clean();

  //================ SETTINGS ================
 	sajax_handle_client_request();

  $smarty->assign("section", "zapata");
  $smarty->assign("subsection", "");
  $smarty->assign("templateType", "TwoColLeft");  //OneCol, TwoColLeft, TwoColRight
  $smarty->assign("contents", $contents);
  $smarty->assign("sidebar", $sidebar);
  $smarty->assign("ajax", $js);
  $smarty->display('settings.tpl');
?>

